from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from goods.models import GoodsCategory, SKU, GoodVisitCount
from meiduo_mall.utils.load_categories import categories_loader
from django.core.paginator import Paginator

from meiduo_mall.utils.mycrumbs import get_crumbs
import time
from datetime import datetime

from meiduo_mall.utils.response_code import RET


class SkuListView(View):
    def get(self, request, category_id, page_num):

        # 面包屑导航
        nav_category = GoodsCategory.objects.get(id=category_id)

        sort = request.GET.get("sort", "default")

        if sort == "default":
            order_method = "-create_time"

        elif sort == "price":
            order_method = "-price"

        else:
            order_method = "sales"

        sku_total = SKU.objects.filter(category_id=nav_category).order_by(order_method)

        paginator = Paginator(object_list=sku_total, per_page=5)

        page = paginator.page(page_num)

        sku = page.object_list

        total_page = paginator.num_pages

        current_page = page.number

        context = {
            "categories": categories_loader(),
            "nav_category": nav_category,
            "sku": sku,
            "current_page": current_page,
            "total_page": total_page,
            "sort": sort
        }

        return render(request, "list.html", context=context)


class HotSkuListView(View):

    def get(self, request, category_id):

        # 获取对象
        hots = SKU.objects.filter(category_id=category_id).order_by("sales")[:3]

        # 拼接对象
        hot_sku_list = []

        for sku in hots:

            sku_dict = {"id":sku.id,
                        "default_image_url":sku.default_image_url.url,
                        "name":sku.name,
                        "price":sku.price}
            hot_sku_list.append(sku_dict)

        data = {"hot_sku_list": hot_sku_list}

        return JsonResponse(data)


class SKUDetailView(View):
    def get(self, request, sku_id):

        # 面包屑导航的渲染
        nav_category = get_crumbs(sku_id)

        # 分类的渲染
        categories = categories_loader()

        # 商品基础信息的渲染
        sku = SKU.objects.get(id=sku_id)

        # TODO 渲染商品的规格选项---------------------理解
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {"categories": categories,
                   "nav_category": nav_category,
                   "sku": sku,
                   'specs': goods_specs}

        return render(request, "detail.html", context=context)


class GoodsVisitView(View):
    def post(self, request, category_id):
        local_time = time.localtime()

        cons_time = "%d-%02d-%02d" % (local_time.tm_year, local_time.tm_mon, local_time.tm_mday)

        my_datetime = datetime.strptime(cons_time, "%Y-%m-%d")

        try:
            result = GoodVisitCount.objects.get(category_id=category_id, date=my_datetime)

        except:
            GoodVisitCount.objects.create(category_id=category_id, date=my_datetime,count=1)

        else:
            result.count += 1
            result.save()

        return JsonResponse({"code": RET.OK})


class ShowSkuComment(View):
    def get(self, request, sku_id):

        sku = SKU.objects.get(id=sku_id)

        sku_sale_goods = sku.ordergoods_set.filter(is_commented=True)

        goods_comment_list = list()

        for sku_sale_good in sku_sale_goods:

            sku_sale_good_comment_dict = {"comment": sku_sale_good.comment,
                                          "name": sku_sale_good.order.user.username,
                                          "score": sku_sale_good.score,
                                          "is_anonymous": sku_sale_good.is_anonymous}

            if sku_sale_good.is_anonymous:
                new_name = "匿名用户"
                sku_sale_good_comment_dict["name"] = new_name

            goods_comment_list.append(sku_sale_good_comment_dict)

        return JsonResponse({"goods_comment_list": goods_comment_list})
